<template>
    <div class="default-main loading">
        <el-row :gutter="30">
            <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="10">
                <div class="admin-info" style="height: 80vh;">
                    <el-upload
                        class="avatar-uploader"
                        action=""
                        :show-file-list="false"
                        @change="onAvatarBeforeUpload"
                        :auto-upload="false"
                        accept="image/gif, image/jpg, image/jpeg, image/bmp, image/png, image/webp"
                        v-if="!isEmpty(state.adminInfo)"
                    >
                        <el-image :src="fullUrl(state.adminInfo.avatar)" class="avatar">
                            <template #error>
                                <div class="image-slot">
                                    <Icon size="30" color="#c0c4cc" name="el-icon-Picture"/>
                                </div>
                            </template>
                        </el-image>
                    </el-upload>
                    <div class="admin-info-base">
                        <div class="admin-nickname">{{ state.adminInfo.nickname }}</div>
                        <div class="admin-other">
                            <div>上次登录于 {{ formatDate(state.adminInfo.last_login_time) }}</div>
                        </div>
                    </div>
                    <div class="admin-info-form">
                        <el-form
                            @keyup.enter="onSubmit()"
                            :key="state.formKey"
                            label-position="top"
                            :rules="rules"
                            ref="formRef"
                            :model="state.adminInfo"
                        >
                            <el-form-item label="用户名">
                                <el-input disabled v-model="state.adminInfo.username"></el-input>
                            </el-form-item>
                            <el-form-item label="姓名" prop="name">
                                <el-input placeholder="姓名" v-model="state.adminInfo.name"></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="mobile">
                                <el-input
                                    placeholder="手机号"
                                    v-model="state.adminInfo.mobile"
                                ></el-input>
                            </el-form-item>

                            <el-form-item label="密码" prop="password">
                                <el-input
                                    type="password"
                                    placeholder="如果未修改，请留空.建议为6-15的字母或者数字可以由纯数字"
                                    v-model="state.adminInfo.password"
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" :loading="state.buttonLoading" @click="onSubmit()">
                                    保存
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </el-col>
            <el-col v-loading="state.logLoading" :xs="24" :sm="24" :md="24" :lg="12">
                <el-card class="scrollable"  header="操作记录" shadow="never" >
                    <el-timeline>
                        <el-timeline-item v-for="(item, idx) in state.log" :key="idx" size="large"
                                          :timestamp="timeFormat(item.create_time)">
                            {{ item.title }}
                        </el-timeline-item>
                    </el-timeline>
                    <el-pagination
                        :currentPage="state.logCurrentPage"
                        :page-size="state.logPageSize"
                        :page-sizes="[12, 22, 52, 100]"
                        background
                        layout="prev, next, jumper"
                        :total="state.logTotal"
                        @size-change="onLogSizeChange"
                        @current-change="onLogCurrentChange"
                    ></el-pagination>
                </el-card>

            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue'
import {actionUrl, index, log, postData} from '/@/api/routine/AdminInfo'
import type {FormInstance, FormItemRule} from 'element-plus'
import {formatDate, fullUrl, onResetForm, timeFormat} from '/@/utils/common'
import {uuid} from '/@/utils/random'
import {buildValidatorData} from '/@/utils/validate'
import {fileUpload} from '/@/api/common'
import {useAdminInfo} from '/@/stores/adminInfo'
import {isEmpty} from 'lodash-es'
import createAxios from "/@/utils/axios";

defineOptions({
    name: 'routine/adminInfo',
})

const formRef = ref<FormInstance>()

const adminInfoStore = useAdminInfo()

const state: {
    adminInfo: anyObj
    formKey: string
    buttonLoading: boolean
    log: {
        title: string
        create_time: string
        url: string
    }[]
    logFilter: anyObj
    logCurrentPage: number
    logPageSize: number
    logTotal: number
    logLoading: boolean
} = reactive({
    adminInfo: {},
    formKey: uuid(),
    buttonLoading: false,
    log: [],
    logFilter: {
        limit: 12,
    },
    logCurrentPage: 1,
    logPageSize: 12,
    logTotal: 100,
    logLoading: true,
})

index().then((res) => {
    state.adminInfo = res.data
    // 重新渲染表单以记录初始值
    state.formKey = uuid()

    // 管理员日志加载，加筛选防止超管读取到其他管理员的日志记录
    state.logFilter.search = [
        {
            field: 'user_id',
            val: String(res.data.id),
            operator: '=',
        },
    ]
    getLog()
})

const getLog = () => {
    createAxios<TableDefaultData>({
        url: '/admin_api/config/user_log',
        method: 'get',
        params: state.logFilter,
    }).then((res) => {
        state.log = res.data.list
        state.logTotal = res.data.total
        state.logLoading = false
    })
        .catch(() => {
            state.logLoading = false
        })
}

const onLogSizeChange = (limit: number) => {
    state.logPageSize = limit
    state.logFilter.limit = limit
    getLog()
}

const onLogCurrentChange = (page: number) => {
    state.logCurrentPage = page
    state.logFilter.page = page
    getLog()
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    nickname: [buildValidatorData({name: 'required', title: '用户名'})],
    email: [buildValidatorData({name: 'email', title: '邮箱'})],

})

const onAvatarBeforeUpload = (file: any) => {
    let fd = new FormData()
    fd.append('file', file.raw)
    fileUpload(fd).then((res) => {
        if (res.code == 0) {
            postData({
                id: state.adminInfo.id,
                avatar: res.data,
            }).then(() => {
                adminInfoStore.dataFill({...adminInfoStore.$state, avatar: res.data})
                state.adminInfo.avatar = res.data
            })
        }
    })
}

const onSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate((valid) => {
        if (valid) {
            let data = {...state.adminInfo}
            delete data.last_login_time
            delete data.username
            delete data.avatar
            state.buttonLoading = true
            postData(data)
                .then(() => {
                    adminInfoStore.dataFill({...adminInfoStore.$state, nickname: state.adminInfo.nickname})
                    state.buttonLoading = false
                })
                .catch(() => {
                    state.buttonLoading = false
                })
        }
    })
}
</script>

<style scoped lang="scss">

.scrollable{
    overflow: auto; /* 自动开启滚动条 */
    height: 80vh; /* 设置最大高度 */
}


.admin-info {
    background-color: var(--ba-bg-color-overlay);
    border-radius: var(--el-border-radius-base);
    border-top: 3px solid #409eff;

    .avatar-uploader {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        margin: 60px auto 10px auto;
        border-radius: 50%;
        box-shadow: var(--el-box-shadow-light);
        border: 1px dashed var(--el-border-color);
        cursor: pointer;
        overflow: hidden;
        width: 110px;
        height: 110px;
    }

    .avatar-uploader:hover {
        border-color: var(--el-color-primary);
    }

    .avatar {
        width: 110px;
        height: 110px;
        display: block;
    }

    .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }

    .admin-info-base {
        .admin-nickname {
            font-size: 22px;
            color: var(--el-text-color-primary);
            text-align: center;
            padding: 8px 0;
        }

        .admin-other {
            color: var(--el-text-color-regular);
            font-size: 14px;
            text-align: center;
            line-height: 20px;
        }
    }

    .admin-info-form {
        padding: 30px;
    }
}

.el-card :deep(.el-timeline-item__icon) {
    font-size: 10px;
}

@media screen and (max-width: 1200px) {
    .lg-mb-20 {
        margin-bottom: 20px;
    }
}
</style>
